# coding=utf-8

from application import app, redis
from common.libs.user.UserLibs import UserLibs
from app.model.mysql.user import User as UserMysql
from app.model.redis.user import User as UserRedis
from app.json.mysql.user import User as UserJson

from app.dao.api.gift import get_list as get_gift_list
from app.dao.api.user_gift import get_list as get_user_gift_list
from app.dao.api.gift_type import get_list as get_gift_type_list



def login_dao(token, email, password):
    """
    登录
    :param token:
    :param email:
    :param password:
    :return:
    """

    user_id = token.split("#")[1] if "#" in token else 0

    if user_id == 0:
        user_model = UserMysql.query.filter(UserMysql.email == email).first()
        if user_model:
            user_model = user_model if UserLibs.genePassword(password, user_model.salt) == user_model.password else None
    else :
        user_model = UserMysql.query.filter(UserMysql.id == user_id).first()

    if user_model:
        user_json = UserJson(user_model).getJson()
        return user_model, user_json
    else :
        return None, None


def login_cache(user_model):
    try:
        token = UserLibs.geneAuthCode(user_model) + "#" + str(user_model.uid)
        redis.sadd(UserRedis.single_login_set.key, token)
        return True
    except :
        return False


def login_check_in_other(token):
    """
    检查是否在别处登录
    :param token:
    :return:
    """
    if not token:
        return False
    user_id = token.split("#")[1] if "#" in token else 0
    if user_id == 0:
        return False
    else :
        return redis.sismember(UserRedis.single_login_set.key, token)


def login_check_wait():
    """
    检查服务器是否已经满员
    :param token:
    :return:
    """
    return redis.scard(UserRedis.single_login_set.key) >= app.config["MAX_CONN"]


def all_info(token):
    result = None
    user_id = token.split("#")[1] if "#" in token else 0
    if user_id == 0:
        return result
    user_gift_list = get_user_gift_list(user_id)
    gift_list = get_gift_list()
    gift_type_list = get_gift_type_list()
    result = {"user_gift_list": user_gift_list,
              "gift_list": gift_list,
              "gift_type_list": gift_type_list}
    return result


def get_user_by_token(token):
    result = None
    user_id = token.split("#")[1] if "#" in token else 0
    if user_id == 0:
        return result

    user_model = UserMysql.query.filter(UserMysql.uid == user_id).first()

    if not user_model:
        return result

    result = UserJson(user_model)
    return result